package dk.ucn.datamatiker.henrik.bundtkage.earthcake.albeheweather;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

//Parser class manages parsing, checks filestypes and finds the right classes that the XML data goes into. 
public class Parser {

	public Parser() {

	}

	// Creates a new XMLPullParser and binds the inputStream to it.
	public XmlPullParser parse(InputStream inputStream)
			throws XmlPullParserException, IOException {
		try {
			XmlPullParser parser = Xml.newPullParser();
			parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
			parser.setInput(inputStream, null);
			return parser;
		} finally {
			inputStream.close();
		}
	}

	// reads the WeatherStream binded in a XmlPullParser and makes a new Weather
	// object with the XML data.
	public Weather readWeatherFeed(XmlPullParser parser)
			throws XmlPullParserException, IOException {
		Weather weather = null;
		// parser.require(XmlPullParser.START_TAG, null, "feed");
		while (parser.next() != XmlPullParser.END_TAG && weather == null) {
			if (parser.getEventType() != XmlPullParser.START_TAG) {
				continue;
			}

			String name = parser.getName();
			// Starts by looking for the entry tag
			if (name.equals("WeatherData")) {
				weather = new Weather(parser);
			} else {
				// skip(parser);
			}
		}
		return weather;
	}

	@SuppressWarnings("rawtypes")
	public ArrayList readLocationsFeed(XmlPullParser parser)
			throws XmlPullParserException, IOException {
		ArrayList<Location> locations = new ArrayList<Location>();
		ArrayList<Location> sortedLocations = new ArrayList<Location>();
		
		while(parser.next() != XmlPullParser.END_TAG){
			if(parser.getEventType() != XmlPullParser.START_TAG) {
				continue;
			}
			
			String name = parser.getName();
			// Starts by looking for the entry tag
			if(name.equals("Location")) {
				locations.add(new Location(parser));
			} else {
				//skip(parser);
			}
		}
		
		for(Location location : locations){
			if(location.getId() != null){
				sortedLocations.add(location);
			}
		}
		return sortedLocations;
	}
}
